package com.example.common.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.common.utils.LogUtil;

public abstract class BaseFragment<T extends ViewDataBinding, V extends BaseViewModel> extends Fragment {
    
    protected T binding;
    protected V viewModel;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LogUtil.d(getClass().getSimpleName(), "onCreateView");
        
        binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
        binding.setLifecycleOwner(this);
        
        viewModel = new ViewModelProvider(this).get(getViewModelClass());
        
        return binding.getRoot();
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
        initObserver();
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtil.d(getClass().getSimpleName(), "onDestroyView");
        if (binding != null) {
            binding.unbind();
        }
    }
    
    protected abstract int getLayoutId();
    
    protected abstract Class<V> getViewModelClass();
    
    protected abstract void initView();
    
    protected abstract void initData();
    
    protected abstract void initObserver();
    
    protected void showLoading() {
        LogUtil.d(getClass().getSimpleName(), "showLoading");
    }
    
    protected void hideLoading() {
        LogUtil.d(getClass().getSimpleName(), "hideLoading");
    }
    
    protected void showError(String error) {
        LogUtil.e(getClass().getSimpleName(), "Error: " + error);
    }
    
    protected void showEmpty() {
        LogUtil.d(getClass().getSimpleName(), "showEmpty");
    }
}